package com.basis.utils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder;

import com.basis.config.DateEditor;
import com.basis.contants.ExceptionEnum;
import com.basis.entity.baseEntity.R;
import com.basis.exception.BizException;

public class ControllerUtils extends R {
	private static Validator validator;

	/**
	 * @Description: 参数验证及转换
	 * @author: lxd
	 * @date: 2019年11月26日 下午2:17:32
	 */
	public static <T> T bindParams(HttpServletRequest request, Class<T> formClz) throws Exception {
		T bindObject = BeanUtils.instantiateClass(formClz);
		ExtendedServletRequestDataBinder dataBinder = new ExtendedServletRequestDataBinder(bindObject, "bindObject");
		dataBinder.setAutoGrowCollectionLimit(1024);
		dataBinder.registerCustomEditor(Date.class, new DateEditor());
		dataBinder.setValidator(getValidator());
		dataBinder.bind(request);
		dataBinder.validate();
		checkErrors(dataBinder.getBindingResult());
		handlerEmpty(bindObject);
		return bindObject;
	}

	private static Validator getValidator() {
		if (validator == null) {
			LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
			localValidatorFactoryBean.afterPropertiesSet();
			validator = localValidatorFactoryBean;
		}
		return validator;
	}

	private static void checkErrors(BindingResult br) throws BizException {
		List<FieldError> errors = br.getFieldErrors();
		if (errors != null && errors.size() > 0) {
			Iterator<FieldError> var2 = errors.iterator();
			if (var2.hasNext()) {
				BizException e = new BizException(ExceptionEnum.SYSTEM_ERRO);
				throw e;
			}
		}

	}

	private static void handlerEmpty(Object object) throws Exception {
		Class<? extends Object> clazz = object.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			if (!field.getName().equals("serialVersionUID")) {
				field.setAccessible(true);
				Object val = field.get(object);
				if (StringUtils.isBlank(String.valueOf(val))) {
					field.set(object, null);
				}
			}
		}

	}

}
